import utilMd5 from 'js-md5'
import excel from '@/libs/excel'
import dataApi from '@/api/data.js'
import { SysAreaApi } from '@/api/SysArea.api.js'
import { SysBasedataApi } from '@/api/SysBasedata.api.js'
import { EmployeesApi } from '../api/Employees.api'
import { EnumApi } from '../api/Enum.api'
import { ReceivableBillApi } from '../api/ReceivableBill.api'
import { FinanceReceivableBillApi } from '@/api/FinanceReceivableBill.api.js'
import { SysWelfarePercentEmployeeConfigApi } from '@/api/SysWelfarePercentEmployeeConfig.api'
import { SysWelfarePercentNoConfigApi } from '@/api/SysWelfarePercentNoConfig.api'
import { FinanceApi } from '@/api/Finance.api'
let Base64 = require('js-base64').Base64

export class Common {
  static warning (str) {
    alert('哈哈哈哈：' + str)
  }

  // 给formItem里的每个select加上options
  static getOptions (form, self) {
    form.map(item => {
      if (item.type === 'select') {
        item.options = self.arrListDown[item.options]
      }
    })
  }

  // setCookie
  static setCookie (name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = name + '=' + escape(value) + ((expiredays === null) ? '' : ';expires=' + exdate.toGMTString())
  }

  // getCookie
  static getCookie (cName) {
    var cStart
    var cEnd
    if (document.cookie.length > 0) {
      cStart = document.cookie.indexOf(cName + '=')
      if (cStart !== -1) {
        cStart = cStart + cName.length + 1
        cEnd = document.cookie.indexOf(';', cStart)
        if (cEnd === -1) cEnd = document.cookie.length
        return unescape(document.cookie.substring(cStart, cEnd))
      }
    }
    return ''
  }

  // delCookie
  static delCookie (name) {
    var exp = new Date()
    exp.setTime(exp.getTime() - 1)
    var cval = this.getCookie(name)
    if (cval !== null) document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
  }

  // sign
  static queryAgentAuthCode (arr) {
    var reqTime = ''
    var authCode = ''
    for (var i = 0; i < 6; i++) {
      authCode += Math.floor(Math.random() * 10)
    }
    reqTime = new Date().getTime()
    // var tempStr = 'agentToken=' + agentToken + '&id=' + id + '&authCode=' + authCode + '&reqTime=' + reqTime
    var tempStr = ''
    for (var j = 0; j < arr.length; j++) {
      tempStr = tempStr.concat(arr[j].name + '=' + arr[j].val + '&')
    }
    var allStr = tempStr + 'authCode=' + authCode + '&reqTime=' + reqTime
    var signStr = Base64.encode(allStr)
    var sign = utilMd5(signStr).toLowerCase()
    var authObj = {
      reqTime: reqTime,
      authCode: authCode,
      sign: sign
    }
    return authObj
  }

  // 表格导出
  static handleExportData (ref, filename) {
    console.log('表格导出: ', ref, ', filename: ', filename)
    ref.exportCsv({
      filename: filename,
      original: false
    })
  }

  static initUpload (importExcel) {
    importExcel.file = null
    importExcel.showProgress = false
    importExcel.loadingProgress = 0
    importExcel.tableData = []
    importExcel.tableTitle = []
  }

  // 读取文件
  static readFile (file, importExcel) {
    const reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onloadstart = e => {
      importExcel.uploadLoading = true
      importExcel.tableLoading = true
      importExcel.showProgress = true
    }
    reader.onprogress = e => {
      this.progressPercent = Math.round(e.loaded / e.total * 100)
    }
    reader.onerror = e => {
      console.log('文件读取出错')
    }
    reader.onload = e => {
      console.log('文件读取成功')
      const data = e.target.result
      const { header, results } = excel.read(data, 'array')
      const tableTitle = header.map(item => { return { title: item, key: item } })
      importExcel.tableData = results
      importExcel.tableTitle = tableTitle
      importExcel.uploadLoading = false
      importExcel.tableLoading = false
      importExcel.showRemoveFile = true
    }
  }

  /**
   * 数据字典
   */
  static getEnum (groupName, arr) {
    let groupArr = groupName.split(',')
    dataApi.getEnum({ groupName: groupName }).then(res => {
      groupArr.map((str, index) => {
        let strArr = str.split('.')
        if (res.data[index].group === str) {
          res.data[index].items.map(item => {
            arr[strArr[1]].push({ label: item.value, value: item.key })
          })
        }
      })
    })
  }

  /**
   * 数据字典(groupName转换小写)
   */
  static getEnum3 (groupName, arr) {
    let groupArr = groupName.split(',')
    dataApi.getEnum({ groupName: groupName }).then(res => {
      groupArr.map((str, index) => {
        let strArr = str.split('.')
        if (res.data[index].group.toLowerCase() === str.toLowerCase()) {
          res.data[index].items.map(item => {
            arr[strArr[1]].push({ label: item.value, value: item.key })
          })
        }
      })
    })
  }

  static getEnum2 (groupName, arr) { // 不带.的groupName
    let groupArr = groupName.split(',')
    dataApi.getEnum({ groupName: groupName }).then(res => {
      groupArr.map((str, index) => {
        // let strArr = str.split('.')
        if (res.data[index].group === str) {
          res.data[index].items.map(item => {
            arr[str].push({ label: item.value, value: item.key })
          })
        }
      })
    })
  }

  /**
   * 数据字典-用工形式/到款银行
   */
  static getSelectValueList (typeName, arr) {
    let typeArr = typeName.split(',')
    dataApi.getSelectValueList({ type: typeName }).then(res => {
      typeArr.map((str) => {
        res.data.data.map(item => {
          arr[str].push({ label: item.text, value: item.value })
        })
      })
    })
  }

  static getSelectIdList (typeName, arr) {
    let typeArr = typeName.split(',')
    SysBasedataApi.getSelectIdList({ type: typeName }).then(res => {
      typeArr.map((str) => {
        arr[str] = []
        res.data.data.map(item => {
          arr[str].push({ label: item.text, value: item.value })
        })
      })
    })
  }

  // 离职原因下拉
  static getLeaveReasonList (typeName, arr) {
    // let typeArr = typeName.split(',')
    SysBasedataApi.getLeaveReasonList({ type: typeName }).then(res => {
      res.data.data.map(item => {
        arr[typeName].push({ label: item.text, value: item.value, isSelect: item.isSelect })
      })
    })
  }

  /**
   * 数据字典-参保区域基数配置
   */
  static getAddModel (params, arr, type) {
    SysWelfarePercentEmployeeConfigApi.getAddModel(params).then(res => {
      res.data.data[type].map(item => {
        arr[type].push({ label: item.text, value: item.value })
      })
    })
  }

  /**
   * 数据字典-获取公司
   */
  static companys (params, arr, type) {
    EnumApi.companys(params).then(res => {
      // res.data.data[type].map(item => {
      //   arr[type].push({label: item.text, value: item.value})
      // })
      res.data.map(item => {
        if (item.group === type) {
          item.items.map(c_item => {
            arr[type].push({ label: c_item.value, value: c_item.key })
          })
        }
      })
    })
  }

  /**
   * 数据字典-获取客服
   */
  static servers (params, arr, type) {
    EnumApi.servers(params).then(res => {
      res.data.map(item => {
        if (item.group === type) {
          item.items.map(c_item => {
            arr[type].push({ label: c_item.value, value: c_item.key })
          })
        }
      })
    })
  }

  /**
   * 数据字典-获取银行下拉
   */
  static getBankList (params, arr, type) {
    EnumApi.getBankList(params).then(res => {
      res.data.data.map(item => {
        arr[type].push({ label: item.bankName, value: item.id, organizationName: item.organizationName, accountName: item.accountName, accountNo: item.accountNo })
      })
    })
  }

  /**
   * 数据字典-获取差额所属项目
   */
  static getBalanceProgramNames (params, arr, type) {
    ReceivableBillApi.getBalanceProgramNames(params).then(res => {
      res.data.data.map(item => {
        arr[type].push({ label: item.name, value: item.code })
      })
    })
  }

  /**
   * 数据字典-获取差额所属项目-new
   */
  static getBalanceProgramNames_new (params, arr, type) {
    FinanceReceivableBillApi.getBalanceProgramNames(params).then(res => {
      res.data.data.map(item => {
        arr[type].push({ label: item.name, value: item.code })
      })
    })
  }

  /**
   * 数据字典-社保方案
   */
  static getPlanList (params, arr, type) {
    SysWelfarePercentNoConfigApi.getPlanList(params).then(res => {
      res.data.data.map(item => {
        arr[type].push({ label: item.text, value: item.value })
      })
    })
  }

  /**
   * 数据字典-获取集团公司
   */
  static getParentCompanys (arr, type) {
    FinanceApi.getParentCompanys().then(res => {
      res.data.data.map(item => {
        arr[type].push({ label: item.companyName, value: item.companyID })
      })
      console.log('❤ 获取集团公司: ', res)
    })
  }

  /**
   * 上一页
   */
  static pageUp (self, gotoPage) {
    self.$emit('page', '-', gotoPage)
  }

  /**
   * 下一页
   */
  static pageDown (self, gotoPage) {
    self.$emit('page', '+', gotoPage)
  }

  /**
   * 时间对象转字符串
   * @param {String} type  yyyy-mm-dd hh:mm:ss 类似数据接口
   * @param {date} value  需要转换的时间对象
   */
  static dealTime (type, value) {
    if (!(value instanceof Date)) {
      return
    }
    let stringDate = ''
    switch (type) {
      case 'yyyy-mm': stringDate = '' + value.getFullYear() + '-' + value.getMonth()
        break
      case 'yyyy-mm-dd': stringDate = '' + value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate()
        break
      case 'yyyy-mm-dd hh-mm': stringDate = '' + value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate() + ' ' + (value.getHours() > 9 ? value.getHours() : '0' + value.getHours()) + ':' + (value.getMinutes() > 9 ? value.getMinutes() : '0' + value.getMinutes())
        break
      case 'yyyy-mm-dd hh-mm-ss': stringDate = '' + value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate() + ' ' + (value.getHours() > 9 ? value.getHours() : '0' + value.getHours()) + ':' + (value.getMinutes() > 9 ? value.getMinutes() : '0' + value.getMinutes()) + ':' + (value.getSeconds() > 9 ? value.getSeconds() : '0' + value.getSeconds())
        break
      default: console.log('请传入需要转换的type格式')
    }
    return stringDate
  }

  /**
   * 根据身份证号计算年龄及性别
   */
  static getAge (IdCardNo, len, form) {
    if (len === 15) { // 15位数的身份证号码 如430923770806001
      var str = IdCardNo.substring(6, 12)
      var year = str.substr(0, 2)
      var month = str.substr(2, 2)
      var date = str.substr(4, 2)
      var birthDayTime = Date.parse(new Date('19' + year + '-' + month + '-' + date))
      form.sex = ((IdCardNo.substr(IdCardNo.length - 1, 1)) % 2 === 0) ? '2' : '1'
      form.age = Math.ceil((new Date().getTime() - birthDayTime) / 31536000000) + ''
      form.birthDay = new Date('19' + year + '-' + month + '-' + date)
      console.log('计算出的年龄是：' + form.age + ', 性别：' + form.sex + ', 生日：' + form.birthDay)
    } else if (len === 18) { // 18位数的身份证号码 如430923199001020011
      var str = IdCardNo.substring(6, 14)
      var year = str.substr(0, 4)
      var month = str.substr(4, 2)
      var date = str.substr(6, 2)
      var birthDayTime = Date.parse(new Date(year + '-' + month + '-' + date))
      form.sex = ((IdCardNo.substr(IdCardNo.length - 2, 1)) % 2 === 0) ? '2' : '1'
      form.age = Math.ceil((new Date().getTime() - birthDayTime) / 31536000000) + ''
      form.birthDay = new Date(year + '-' + month + '-' + date)
      console.log('计算出的年龄是：' + form.age + ', 性别：' + form.sex + ', 生日：' + form.birthDay)
    }
  }

  /**
   * 数组去重
   */
  static ToHeavy (arr) {
    if (arr.length) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i].txt === arr[j].txt) {
            arr.splice(j, 1)
            j--
          }
        }
      }
    }
  }

  /**
   * 数组去重2
   */
  static ToHeavy2 (arr, key) {
    if (arr.length) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i][key] === arr[j][key]) {
            arr.splice(j, 1)
            j--
          }
        }
      }
    }
    return arr
  }

  /**
   * 数组去重3
   */
  static ToHeavy3 (arr) {
    if (arr.length) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i] === arr[j]) {
            arr.splice(j, 1)
            j--
          }
        }
      }
    }
    return arr
  }

  /**
   * 验证身份证号码
   */
  static validateIdCardNo = (rule, value, callback) => {
    var vnum = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    var vyear = /^(19|20)\d{2}$/
    var vmonth = /^(0[1-9]|1[0-2])$/
    var vdate = /^(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/
    var vsame = /(\w)*(\w)\2{2}(\w)*/g
    if (!vnum.test(value)) {
      callback(new Error('请输入15或18位身份证号码'))
    } else {
      if (value.length === 15) {
        var str = value.substring(6, 12)
        var year = str.substr(0, 2)
        var month = str.substr(2, 2)
        var date = str.substr(4, 2)
        // else if (vsame.test(value)) {
        //   callback(new Error('不允许输入连续3位相同的数字'))
        // }
        if (!vmonth.test(month)) {
          callback(new Error('请输入正确的月份'))
        } else if (!vdate.test(date)) {
          callback(new Error('请输入正确的出生日期'))
        } else {
          callback()
        }
      } else if (value.length === 18) {
        var str = value.substring(6, 14)
        var year = str.substr(0, 4)
        var month = str.substr(4, 2)
        var date = str.substr(6, 2)
        // else if (vsame.test(value)) {
        //   callback(new Error('不允许输入连续3位相同的数字'))
        // }
        if (!vmonth.test(month)) {
          callback(new Error('请输入正确的月份'))
        } else if (!vdate.test(date)) {
          callback(new Error('请输入正确的出生日期'))
        } else {
          callback()
        }
      }
      // callback()
    }
  }

  /**
   * 验证带有小数点的数字（不能为负）
   */
  static validatePatrnNo = (rule, value, callback) => {
    var vnum = /^\d+(\.\d{1,2})?$/
    if (value.indexOf('-') !== -1) {
      callback(new Error('不能输入负数'))
    } else if (!vnum.test(value)) {
      callback(new Error('请输入小数点后的数字并且不能超过2位'))
    } else {
      callback()
    }
  }

  /**
   * 日期转换（用于日历）
   */
  static baseToDate (date, moment) {
    let toDate = moment(new Date(('20' + date).replace(/([^\u0000-\u00FF])/g, '/').substr(0, 10))).format('YYYY-MM-DD')
    return toDate
  }

  // 设置表头
  static getTableColumns (arr, tableColumns) {
    let data = []
    arr.forEach(col => data.push(tableColumns[col]))
    return data
  }
}
